import React, { useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import CryptoJS from 'crypto-js';

export interface Wallet {
  encrypted: string;
  seed: string;
  address: string;
  memo: string;
  exported: boolean;
}

export function checkPassword(wallet: Wallet, password: string): boolean {
  try {
    const seed = CryptoJS.AES.decrypt(wallet.encrypted, password).toString(CryptoJS.enc.Utf8);
    return seed === wallet.seed;
  } catch (e) {
    return false;
  }
}

export const useWallet = (): [boolean, Wallet | null, (w: Wallet) => void] => {
  const [load, setLoad] = useState(false);
  const [wallet, setWallet] = useState<Wallet | null>(null);

  const wrapSetWallet = (wallet: Wallet | null) => {
    const work = async () => {
      setWallet(wallet);

      const w = wallet === null ? '' : JSON.stringify(wallet);
      try {
        await AsyncStorage.setItem('@wallet', w);
      } catch (e) {
        console.log('@wallet set', e);
      }
    };

    work();
  };

  useEffect(() => {
    const work = async () => {
      try {
        const w = await AsyncStorage.getItem('@wallet');
        setWallet(w ? JSON.parse(w) : null);
      } catch (e) {
        console.log('@wallet get', e);
      }

      setLoad(true);
    };

    work();
  }, []);

  return [load, wallet, wrapSetWallet];
};

const WalletContext = React.createContext<Wallet | null>(null);

export default WalletContext;